import React from "react";


import _get from 'lodash/get';

import {
  anchor,
  tastArr,
  eventArr,
  gatewayArr,
  taskShapStyle,
} from "./flowConfig";
import { staticModel } from "./structureData";
// import G6Editor from "@antv/g6-editor";

const G6Editor = require('../../g6-editor/src')

const { Flow } = G6Editor;
/* 注册任务节点 */
Flow.registerNode("task-card", {
  draw(item) {
    const group = item.getGraphicGroup();
    const model = item.getModel();
    const width = 116;
    const height = 60;
    const x = -width / 2;
    const y = -height / 2;
    const borderRadius = 4;
    const keyShape = group.addShape("rect", {
      attrs: {
        x,
        y,
        width,
        height,
        radius: borderRadius,
        // fill: "#fff",
        lineWidth: 2,
        stroke: model.status ? "#027722" : "#FFBB95",
        fill: _get(window, 'FLOW_THEME.highlightColor', '#fff'),
        // stroke: _get(window, 'FLOW_THEME.color', "#FFBB95"),
      },
    });
    // 类型 logo
    group.addShape("image", {
      attrs: {
        img: this.type_icon_url,
        x: -20 / 2,
        y: y + 8,
        width: 20,
        height: 20,
        // fill: "#fff",
        stroke: "#FFBB95",
        fill: _get(window, 'FLOW_THEME.highlightColor', '#fff'),
        // stroke: _get(window, 'FLOW_THEME.color', '#FFBB95'),
      },
    });
    // 名称文本
    const label = model.label ? model.label : this.label;
    group.addShape("text", {
      attrs: {
        text: label,
        x: 0,
        y: 6,
        textAlign: "center",
        textBaseline: "top",
        // fill: "rgba(0,0,0,0.65)",
        fill: _get(window, 'FLOW_THEME.color', 'rgba(0,0,0,0.65)'),
      },
    });

    return keyShape;
  },
  // 设置锚点
  // anchor
});

/* 注册事件节点 */
Flow.registerNode("event-card", {
  draw(item) {
    const group = item.getGraphicGroup();
    const model = item.getModel();
    const imgWaH = 32;
    const imgx = -imgWaH / 2;
    const imgy = -imgWaH / 2;
    const r = imgWaH / 2 - 2;

    const keyShape = group.addShape("circle", {
      attrs: {
        x: 0,
        y: 0,
        r,
        // fill: "#fff",
        stroke: "#ccc",
        fill: _get(window, 'FLOW_THEME.highlightColor', '#fff'),
        // stroke: _get(window, 'FLOW_THEME.color', '#ccc'),
      },
    });
    // 类型 logo
    group.addShape("image", {
      attrs: {
        img: this.type_icon_url,
        x: imgx,
        y: imgy,
        width: imgWaH,
        height: imgWaH,
      },
    });
    const label = model.label ? model.label : this.label;
    group.addShape("text", {
      attrs: {
        text: label,
        x: 0,
        y: 24,
        textAlign: "center",
        textBaseline: "top",
        // fill: "rgba(0,0,0,0.75)",
        fill: _get(window, 'FLOW_THEME.color', 'rgba(0,0,0,0.75)'),
      },
    });
    return keyShape;
  },
  // 设置锚点
  anchor,
});

Flow.registerNode("gateway-card", {
  draw(item) {
    const group = item.getGraphicGroup();
    const model = item.getModel();
    const imgWaH = 38;
    const imgx = -imgWaH / 2;
    const imgy = -imgWaH / 2;
    const label = model.label ? model.label : this.label;
    const keyShape = group.addShape("rect", {
      attrs: {
        x: imgx,
        y: imgx,
        width: imgWaH,
        height: imgWaH,
        radius: 4,
      },
    });
    group.addShape("text", {
      attrs: {
        text: label,
        x: 0,
        y: 26,
        textAlign: "center",
        textBaseline: "top",
        // fill: "rgba(0,0,0,0.75)",
        fill: _get(window, 'FLOW_THEME.color', 'rgba(0,0,0,0.75)'),
      },
    });
    group.addShape("image", {
      attrs: {
        img: this.type_icon_url,
        x: imgx,
        y: imgy,
        width: imgWaH,
        height: imgWaH,
      },
    });
    return keyShape;
  },
  // 设置锚点
  anchor,
});

eventArr.forEach((item) => {
  Flow.registerNode(
    item.shape,
    {
      label: item.label,
      color_type: item.color_type,
      type_icon_url: item.type_icon_url,
      // 设置锚点
      anchor: item.anchor || anchor,
    },
    "event-card",
  );
});

gatewayArr.forEach((item) => {
  Flow.registerNode(
    item.shape,
    {
      label: item.label,
      color_type: item.color_type,
      type_icon_url: item.type_icon_url,
      // 设置锚点
      anchor: item.anchor || anchor,
    },
    "gateway-card",
  );
});

tastArr.forEach((item) => {
  // 读数据表
  Flow.registerNode(
    item.shape,
    {
      label: item.label,
      color_type: item.color_type,
      type_icon_url: item.type_icon_url,
      // 设置锚点
      anchor: item.anchor || anchor,
    },
    "task-card",
  );
});

export default class Editor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // 当前选中项数据模型
      selectedModel: {}, // eslint-disable-line
    };
  }

  componentWillMount() { // eslint-disable-line
    this.editor = new G6Editor();
  }

  componentDidMount() {
    const { editor } = this;
    const pages = editor.getComponentsByType("page");
    pages.forEach((page) => {
      page.on("afteritemselected", (ev) => {
        this.setState({
          selectedModel: ev.item.getModel(),
        });
      });

      page.on("afteritemunselected", () => {
        this.setState({
          selectedModel: {},
        });
      });



      page.on("beforechange", (ev) => {
        const { action, model = {} } = ev;
        switch (action) {
          case "add":
            model.style = taskShapStyle[model.shape] || {};
            if (model.shape === "flow-polyline-round") {
              const sourceItemModel = this.getItemById(model.source);
              if (
                gatewayArr.some(
                  (item) =>
                    item.shape === sourceItemModel.shape && item.show_condition,
                )
              ) {
                model.gatewaySource = true; // 线的源是网关设置页面展示标志为true
              }
            }
            break;
          default:
            break;
        }
      });

      page.on("afterchange", (ev) => {
        const { action, item, model = {} } = ev;
        const { shape = "" } = model;

        const graph = page.getGraph();

        switch (action) {
          case "add":
            model.model = staticModel[shape] || {}; // 添加节点，初始化后端传参的数据放到model里
            model.model.resourceId = model.id; // 添加节点，初始化后端传参的数据放到model里
            model.model.name = model.lable; // 添加节点，初始化后端传参的数据放到model里
            page.clearSelected(); // 先清选中项
            page.setSelected(item, true); // 设置当前添加的项为选中状态

            if (model.shape === "GroupTask") {
              page.addGroup({
                id: `${model.id}Group`,
                label: '子流程',
                shape:'Subprocess',
                model:{
                  properties: {
                    overrideid: "",
                    name: "子流程",
                    documentation: "",
                  },
                },
                stencil: {
                  id: "Subprocess",
                },
              });
              page.remove(item);
              const { x, y } = model;
              const startModel = {
                key: "41",
                style: taskShapStyle.GroupTaskStart || {},
                shape: "GroupTaskStart",
                type: "node",
                size: "32*32",
                color: "#fff",
                label: "子流程开始",
                prefixType: "Zcon",
                prefixValue: "circle-o",
                id: `${model.id}GroupStart`,
                parent: `${model.id}Group`,
                x: x - 110,
                y,
                model:{
                  properties: {
                    overrideid: "groupstart",
                    name: "子流程开始",
                    documentation: "",
                    executionlisteners: "",
                    initiator: "",
                    formkeydefinition: "",
                    formreference: "",
                    formproperties: {},
                    conditionsequenceflow:'',
                  },
                  stencil: {
                    id: "StartNoneEvent",
                  },
                },

              }

              const endModel = {
                style: taskShapStyle.GroupTaskEnd || {},
                key: "42",
                shape: "GroupTaskEnd",
                type: "node",
                size: "32*32",
                color: "#fff",
                label: "子流程结束",
                prefixType: "Zcon",
                prefixValue: "pitch-on",
                id: `${model.id}GroupEnd`,
                parent: `${model.id}Group`,
                x: x + 110,
                y,
                model:{
                  properties: {
                    overrideid: "groupend",
                    name: "子流程結束",
                    documentation: "",
                    executionlisteners: "",
                    initiator: "",
                    formkeydefinition: "",
                    formreference: "",
                    formproperties: {},
                    conditionsequenceflow:'',
                  },
                  stencil: {
                    id: "EndNoneEvent",
                  },
                },

              }

              graph.add('node', startModel);
              graph.add('node', endModel);
              page.clearSelected(); // 先清选中项
            }
            break;
          case "remove":
            page.clearSelected(); // 先清选中项
            this.setState({ selectedModel: {}});
            // page.setSelected(item, false);
            break;

          case "update":
            {
              const pageq = this.editor.getCurrentPage();
              const edges = pageq?.getEdges() || [];
              edges.map(edge => {
                graph.toFront(edge);
                return edge
              })
            }
            break;
          default:
            break;
        }
      });
    });
  }

  getSelectedModel = () => {
    const { selectedModel } = this.state;
    return selectedModel;
  };

  getItemById = (id) => {
    const page = this.editor.getCurrentPage();
    const nodes = page.getNodes();
    const newItems = nodes.filter((item) => {
      const { model } = item;
      return model.id === id;
    });
    const itemObj = newItems.length > 0 ? newItems[0].model || {} : {};
    return itemObj;
  };

  getNodes = () => {
    const page = this.editor.getCurrentPage();
    const nodes = page.getNodes() || [];
    return nodes;
  };

  // getEdges = () => {
  //   const page = this.editor.getCurrentPage();
  //   const edges = page.getEdges() || [];
  //   return edges;
  // };

  updateGraph = (key, value) => {
    const { editor } = this;
    editor.executeCommand(() => {
      const page = editor.getCurrentPage();
      const selectedItems = page.getSelected();
      selectedItems.forEach((item) => {
        const updateModel = {};
        updateModel[key] = value;
        if (key === "label") {
          const { model: itemModel } = item;
          const { model = {} } = itemModel;
          const { properties = {} } = model;
          const newobj = { name: value };
          const newModel = {
            ...model,
            properties: { ...properties, ...newobj },
          };

        // if (newModel.hasOwnProperty('bounds') && _isEmpty(newobj.bounds)) {
        //   newModel = _omit(newModel, ['bounds']);
        // }

        // if (newModel.hasOwnProperty('childShapes') && _isEmpty(newobj.childShapes)) {
        //   newModel = _omit(newModel, ['childShapes']);
        // }

        // if (newModel.hasOwnProperty('dockers') && _isEmpty(newobj.dockers)) {
        //   newModel = _omit(newModel, ['dockers']);
        // }

        // if (newModel.hasOwnProperty('node') && _isEmpty(newobj.node)) {
        //   newModel = _omit(newModel, ['node']);
        // }

        // if (newModel.hasOwnProperty('outgoing') && _isEmpty(newobj.outgoing)) {
        //   newModel = _omit(newModel, ['outgoing']);
        // }

        // if (newModel.hasOwnProperty('target') && _isEmpty(newobj.target)) {
        //   newModel = _omit(newModel, ['target']);
        // }

        // newModel.properties.usertaskassignment = '';
        // newModel.properties.copyTo = null;
        // newModel.properties.httpcallback = { isEmpty: true, parameters: [], url:null },
          // "bounds": null,
          // "childShapes": null,
          // "dockers": null,
          // "node": null,
          // "outgoing": null,
          // target


          // copyTo
          //       "httpcallback": { "isEmpty": true, "parameters": [] },

          // newModel.resourceId = newModel.resourceId.replace(/id/, '');
          updateModel.model = newModel;
        }
        page.update(item, updateModel);
      });
    });
  };
}
